package com.lizhi.controller;

import com.lizhi.dto.CompleteResult;
import com.lizhi.entity.LocalTask;
import com.lizhi.mapper.LocalTaskMapper;
import com.lizhi.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @author : 芝麻
 * @date : 2023-08-20 09:32
 **/
@RestController
@RequestMapping("zhima-task")
public class ZhimaLocalTaskController {
    @Autowired
    private TaskService taskService;

    @Autowired
    private LocalTaskMapper localTaskMapper;

    @PostMapping("/publish/{taskType}")
    public boolean publishTask(@PathVariable("taskType") String taskType, @RequestBody List<String> businessKeys) {
        return taskService.publishTask(taskType, businessKeys);
    }

    @GetMapping("/all")
    public List<LocalTask> all() {
        return localTaskMapper.selectList(null);
    }

    @GetMapping("/dispatchTasks/{taskType}/{limit}")
    public List<LocalTask> dispatchTasks(@PathVariable("taskType") String taskType, @PathVariable("limit") Integer limit) {
        return taskService.dispatchTasks(taskType, limit);
    }

    @GetMapping("/dispatchTasks/{shardSize}/{shardIndex}/{taskType}/{limit}")
    public List<LocalTask> dispatchTasksBasedOnShared(@PathVariable("shardSize") Integer shardSize, @PathVariable("shardIndex") Integer shardIndex, @PathVariable("taskType") String taskType, @PathVariable("limit") Integer limit) {
        return taskService.dispatchTasks(taskType, shardSize, shardIndex, limit);
    }

    @PostMapping("/completeSubTask/{taskId}")
    public boolean completeSubTaskWithSubTaskIndex(@PathVariable("taskId") Integer taskId, CompleteResult completeResult) {
        if (completeResult.getSubTaskIndex() != null) {
            return taskService.completeSubTask(taskId, completeResult.getSubTaskIndex(), completeResult.getErrorMessage());
        } else {
            return taskService.completeSubTask(taskId, completeResult.getErrorMessage());
        }
    }

    @PostMapping("/startSubtask/{taskId}/{subTaskIndex}")
    public boolean startSubTaskWithSubTaskIndex(@PathVariable("taskId") Integer taskId,
                                                @PathVariable("subTaskIndex") Integer subTaskIndex) {
        return taskService.startSubTask(taskId, subTaskIndex);
    }

    @PostMapping("/startSubtask/{taskId}")
    public boolean startSubTaskWithoutSubTaskIndex(@PathVariable("taskId") Integer taskId) {
        return taskService.startSubTask(taskId);
    }
}
